import Vue from 'vue'
import VueRouter from 'vue-router'
import store from '@/store/index'
import { getUser } from '@/api/login.js'
import { getlocal } from '@/utils/local.js'

Vue.use(VueRouter)

const routes = [
  {
    path: '/',
    alias: '/login',
    component: () => import('@/views/login/login.vue')
  },
  {
    path: '/table',
    redirect: '/table/my', // 重定向到我的
    component: () => import('@/views/layout/table.vue'),
    children: [
      // 配置子路由
      {
        path: 'home', // home页面
        component: () => import('@/views/layout/home/home.vue'),
        meta: { needTab: true }
      },
      {
        path: 'my', // home页面
        component: () => import('@/views/layout/my/my.vue'),
        meta: { needLogin: true, needTab: true }
      },
      {
        path: 'myInfo', // my页面
        component: () => import('@/views/layout/my/myInfo.vue'),
        meta: { needLogin: true }
      },
      {
        path: 'video', // video页面
        component: () => import('@/views/layout/video/video.vue'),
        meta: { needTab: true }
      },
      {
        path: 'search', // search页面
        component: () => import('@/views/layout/search/search.vue'),
        meta: { needTab: true }
      },
      {
        path: 'searchList', // 搜索列表页面
        component: () => import('@/views/layout/search/searchList.vue')
      },
      {
        path: 'searchdetail', // 文章详情
        component: () => import('@/views/layout/search/searchdetail.vue')
      }
    ]
  }
]

const router = new VueRouter({
  routes
})

// 路由前置守卫
router.beforeEach(async (to, from, next) => {
  console.log('to', to)
  if (to.meta.needLogin) {
    if (store.state.isLogin) {
      // 如果是true过
      next()
    } else {
      // 判断有没有token
      if (getlocal()) {
        // 有token,发送请求获取用户信息
        const res = await getUser()
        console.log('用户', res)
        // 存储用户信息在vuex
        store.commit('setUserInfo', res.data.data)
        // 修改登陆状态
        store.commit('setIslogin', true)
        next()
      } else {
        // 回跳登陆页,携带回跳地址
        next('/login?redirect=' + window.location.href.split('#')[1])
      }
    }
  } else {
    next()
  }
})

// 路由后置守卫

// 解决路由错误的,百度
const originalPush = VueRouter.prototype.push

VueRouter.prototype.push = function push (location) {
  return originalPush.call(this, location).catch(err => err)
}

export default router
